//
//  ZLAlertAnimation.swift
//  ZLAlert
//
//  Created by ZL on 2022/11/24.
//

import Foundation

/// 动画
class ZLAlertAnimation : NSObject, UIViewControllerAnimatedTransitioning {

    let isPresenting: Bool
    
    init(isPresenting: Bool) {
        self.isPresenting = isPresenting
    }
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        if (isPresenting) {
            return 0.45
        } else {
            return 0.1
        }
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        if (isPresenting) {
            self.presentAnimateTransition(transitionContext)
        } else {
            self.dismissAnimateTransition(transitionContext)
        }
    }
    
    func presentAnimateTransition(_ transitionContext: UIViewControllerContextTransitioning) {
        
        let alertController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! ZLAlert
        let containerView = transitionContext.containerView
        
        alertController.mainView.alpha = 0.0
        alertController.mainView.alpha = 0.0
        alertController.mainView.center = alertController.view.center
        alertController.mainView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
        alertController.view.backgroundColor = UIColor.init(white: 0, alpha: 0)
        containerView.addSubview(alertController.view)
        
        UIView.animate(withDuration: 0.15, animations: {
            alertController.mainView.alpha = 1.0
            alertController.mainView.transform = CGAffineTransform(scaleX: 1.02, y: 1.02)
            alertController.view.backgroundColor = UIColor.init(white: 0, alpha: 0.2)
        }, completion: { finished in
            UIView.animate(withDuration: 0.05, animations: {
                alertController.mainView.transform = CGAffineTransform.identity
            }, completion: { finished in
                if (finished) {
                    transitionContext.completeTransition(true)
                }
            })
        })
    }
    
    func dismissAnimateTransition(_ transitionContext: UIViewControllerContextTransitioning) {
        
        let alertController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as! ZLAlert
        
        UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: {
            alertController.mainView.alpha = 0.0
            alertController.mainView.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
            alertController.view.backgroundColor = UIColor.init(white: 0, alpha: 0)
        }, completion: { finished in
            transitionContext.completeTransition(true)
        })
    }
}
